from django import forms
from django.core import validators
from .models import Article

class MessageBoardForm(forms.Form):
    title = forms.CharField(min_length=2, max_length=50, label='标题',
                            error_messages={
                                "min_length": '标签长度最小不能少于2！',
                                'max_length': '标签长度最大不能超过50'
                            })
    content = forms.CharField(widget=forms.Textarea, label='内容')
    email = forms.EmailField(label='邮箱')

class RegisterForm(forms.Form):
    telephone = forms.CharField(validators=[validators.RegexValidator(r'1[345678]\d{9}', message='手机号码格式不符合!')])
    pwd1 = forms.CharField(min_length=6, max_length=100)
    pwd2 = forms.CharField(min_length=6, max_length=100)

    # 专门针对telephone字段进行验证
    def clean_telephone(self):
        telephone = self.cleaned_data['telephone']
        if telephone == '15978853471':
            raise forms.ValidationError('手机号码已经存在！')
        else:
            return telephone

    # 对多个字段进行验证，重写clean方法
    def clean(self):
        # 调用父类的clean方法
        cleaned_data = super().clean()
        pwd1 = cleaned_data.get('pwd1')
        pwd2 = cleaned_data.get('pwd2')
        if pwd1 != pwd2:
            raise forms.ValidationError("两次密码不一致！")
        else:
            return cleaned_data

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        # fields = '__all__'
        # fields = ['title', 'content']
        exclude = ['category']

        # 自定义错误消息
        error_messages = {
            'title': {
                'required': 'title不能为空'
            }
        }